#!/bin/bash
# Author: Xun Deng

### Prepare
if ! [ -f '.config' ]; then
    echo "must specify a kernel config"
    exit 1
fi

. setup.sh # source
if [ -z "${DXOS_OSNAME}" ]; then
    echo 'setup error'
    exit 2
fi

### Build Kernel
kernel_dir="linux-${DXOS_KERNEL_VERSION}"
kernel_file="${kernel_dir}.tar.xz"

if ! [ -e "${kernel_file}" ]; then
    echo "Download ${kernel_file} from ${DXOS_KERNEL_BASEURL}"
    wget "${DXOS_KERNEL_BASEURL}${kernel_file}"
    rm -rf "${kernel_dir}"
fi

if ! [ -f 'bzImage' ]; then

    if ! [ -d "${kernel_dir}" ]; then
        tar -xJpf ${kernel_file}
    fi

    if ! [ -d "${kernel_dir}" ]; then
        echo 'kernel directory not exists'
        exit 4
    fi

    echo 'build kernel'
    cp .config "${kernel_dir}/"
    cd "${kernel_dir}"
    make -j64
    cd - >/dev/null # go back
    cp "${kernel_dir}/arch/x86/boot/bzImage" .
fi

### System Initrd
if ! [ -d 'initrd' ]; then
    tar -xJpf 'initrd.tar.xz'
fi

# mkinit.sh
# os.sh

cd 'initrd'
find . | cpio -H newc -o | xz -T 0 -9 --check=crc32 >'../initrd.img'
cd ..

# grubins.sh
